require 'fileutils'


def build_extension(name, arch, src_files)
  objects = []
  mkdir_p $tempdir unless File.exist? $tempdir

  src_files.each do |f|
    objname = File.join( $tempdir, File.basename( f.gsub(/\.c$/, '.o') ) )
    objects << ('"'+objname+'"')

    args = []
    args << "-I."
    args << "-I\"#{$rootdir}/platform/android/Rhodes/jni/include\""
    args << "-I\"#{$rootdir}/platform/shared/ruby/include\""
    args << "-I\"#{$rootdir}/platform/shared\""
    args << "-I\"#{$rootdir}/platform/shared/common\""
    args << "-I\"#{$rootdir}/platform/shared/ruby/android\""
    args << "-I\"#{$rootdir}/platform/shared/ruby/generated\""

    cc_compile f, $tempdir, args or exit 1

  end

  mkdir_p $targetdir unless File.exist? $targetdir

   cc_ar (File.join( $targetdir,'armeabi','lib' + name + '.a' )), Dir.glob($tempdir + "/**/*.o").collect{|x| '"'+x+'"'} or exit 1

end

namespace "build" do
  task :config do
    curdir = pwd
    $audiocapturedir = curdir.gsub('/ext/audiocapture/platform/android','');
    $targetdir = ENV['TARGET_TEMP_DIR']
    raise "TARGET_TEMP_DIR is not set" if $targetdir.nil?
    $tempdir = ENV['TEMP_FILES_DIR']
    raise "TEMP_FILES_DIR is not set" if $tempdir.nil?
    $rootdir = ENV['RHO_ROOT']
    raise "RHO_ROOT is not set" if $rootdir.nil?

    require File.join($rootdir, 'platform/android/build/androidcommon.rb')

    setup_ndk(ENV['ANDROID_NDK'],ENV['ANDROID_API_LEVEL'])

  end

  task :all => :config do

    src_files = []

    src_files << $audiocapturedir + '/ext/audiocapture/platform/android/jni/src/audiocapture.cpp'
    src_files << $audiocapturedir + '/ext/audiocapture/shared/ruby/audiocapture_wrap.c'
    src_files << $audiocapturedir + '/ext/audiocapture/shared/src/audiocapture.c'

    # build native part
    build_extension('audioCapture', $arch, src_files)

    # java part will be builded automatically (java files should be listed in ext_build.files ans ext. yml should be configured)

  end
end

task :default => "build:all"
